package com.cj.mobile.iabp.mvp.ui.activity;

import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.app.dialog.PopupSelectFinancial;
import com.cj.mobile.iabp.app.dialog.PopupTipsDialog;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.di.component.DaggerHomePatientComponent;
import com.cj.mobile.iabp.mvp.contract.HomePatientContract;
import com.cj.mobile.iabp.mvp.model.entity.DeptInfo;
import com.cj.mobile.iabp.mvp.model.entity.PatientInfo;
import com.cj.mobile.iabp.mvp.presenter.HomePatientPresenter;
import com.cj.mobile.iabp.mvp.ui.adapter.PatientInfoAdapter;
import com.jakewharton.rxbinding3.widget.RxTextView;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created on 2025/09/02 22:49
 * 首页患者
 *
 * @author Love_xie
 * module name is HomePatientActivity
 */
public class HomePatientActivity extends BaseActivity<HomePatientPresenter> implements HomePatientContract.View, DefaultAdapter.OnRecyclerViewItemClickListener {

    /*-------------------------------------------控件信息-------------------------------------------*/
    @BindView(R.id.edit_homepatient_input)
    EditText editInput;                                                                             // 搜索
    @BindView(R.id.imvi_homepatient_clear)
    ImageView imviClear;

    @BindView(R.id.tab_homepatient_group)
    RadioGroup viewTabGroup;                                                                        // Tab
    @BindView(R.id.radio_homepatient_chaoyang)
    RadioButton radioCY;
    @BindView(R.id.radio_homepatient_tongzhou)
    RadioButton radioTZ;

    @BindView(R.id.revi_homepatient_content)
    RecyclerView mRecyclerView;                                                                     // 列表

    @BindView(R.id.lila_homepatient_notdata)
    LinearLayout notData;

    @BindView(R.id.linla_homepatient_loading)
    View loading;                                                                                   // 加载效果

    @BindView(R.id.txvi_homepatient_department)
    TextView txviDepartment;

    /*-------------------------------------------业务信息-------------------------------------------*/

    // 是否初始化edit
    private boolean isInit;
    // 科室 弹框
    private PopupSelectFinancial mPopupDepartment;
    @Inject
    RecyclerView.LayoutManager mLayoutManager;

    @Inject
    PatientInfoAdapter mAdapter;
    /**
     * 对话框
     */
    private MaterialDialog mDialog;

    @Override
    public void onDestroy() {
        // super.onDestroy()之后会unbind,所有view被置为null,所以必须在之前调用
        DefaultAdapter.releaseAllHolder(mRecyclerView);
        if (mDialog != null) {
            this.mDialog.dismiss();
        }
        super.onDestroy();
        this.mDialog = null;

        this.mLayoutManager = null;
        this.mAdapter = null;
        this.mPopupDepartment = null;
    }

    /**
     * 根据主题使用不同的颜色。
     * 如果想要纯透明，则需要重写此方法，返回值为 -1 即可。
     */
    public int useStatusBarColor() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(android.R.color.white, typedValue, true);
        return typedValue.data;
    }

    /**
     * 将状态栏改为浅色模式(状态栏 icon 和字体会变成深色)
     */
    public boolean useLightStatusBar() {
        return true;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHomePatientComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_home_patient;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        // 初始化Loading对话框
        mDialog = new MaterialDialog.Builder(this).content(R.string.common_execute).progress(true, 0).cancelable(false).build();

        if (mPresenter != null) {
            mPresenter.initData(getIntent().getExtras());
        }

        initEdit();
        // 初始化RecyclerView
        initRecyclerView();

        // Tab 切换监听
        viewTabGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.radio_homepatient_chaoyang) {
                if (mPresenter != null) {
                    mPresenter.setDeptSec("2");
                }
                radioCY.setTextColor(getResources().getColor(R.color.common_edit_color));
                radioCY.setBackgroundResource(R.drawable.financial_bg_white_shape);

                radioTZ.setTextColor(getResources().getColor(R.color.common_text_hint_color));
                radioTZ.setBackground(null);
                // 此处可添加“朝阳院区”选中后的业务逻辑
            } else if (checkedId == R.id.radio_homepatient_tongzhou) {
                if (mPresenter != null) {
                    mPresenter.setDeptSec("3");
                }
                radioTZ.setTextColor(getResources().getColor(R.color.common_edit_color));
                radioTZ.setBackgroundResource(R.drawable.financial_bg_white_shape);
                radioCY.setTextColor(getResources().getColor(R.color.common_text_hint_color));
                radioCY.setBackground(null);
                // 此处可添加“通州院区”选中后的业务逻辑
            }

            loadData();
        });
    }


    @SuppressLint("CheckResult")
    private void initEdit() {
        RxTextView.textChanges(editInput)
                .debounce(800, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(charSequence -> {
                    if (isInit) {
                        String val = charSequence.toString();
                        if (!TextUtils.isEmpty(val)) {
                            imviClear.setVisibility(View.VISIBLE);

                            hideInput();
                            if (mPresenter != null) {
                                mPresenter.setKey(val);
                            }
                            loadData();
                        } else {
                            imviClear.setVisibility(View.GONE);
                        }
                    } else {
                        isInit = true;
                    }

                });
    }


    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
    }

    /**
     * 加载数据
     */
    private void loadData() {
        if (mPresenter != null)
            mPresenter.getPatientInfo(false);
    }

    @OnClick({
            R.id.imvi_homepatient_clear,                                                            // 清除数据
            R.id.lila_homepatient_department,                                                       // 筛选 - 科室
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imvi_homepatient_clear:                                                       // 清除数据
                editInput.setText("");
                if (mPresenter != null) {
                    mPresenter.setKey("");
                }
                loadData();
                break;
            case R.id.lila_homepatient_department:                                                  // 筛选 - 科室
                if (mPopupDepartment != null) {
                    mPopupDepartment.showAtLocation(v, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
                } else {
                    showMessage("暂无科室数据，请联系管理员！");
                }
                break;
        }
    }

    @Override
    public void onItemClick(@NonNull View view, int viewType, @NonNull Object data, int position) {
        if (view.getId() == R.id.tv_opt_select) {
            // 查看
            PatientInfo info = (PatientInfo) data;
            Bundle mBundle = new Bundle();
            mBundle.putString("id", info.getId());
            ActivityUtils.startActivity(mBundle, PatientInfoActivity.class);
        } else if (view.getId() == R.id.tv_opt_del) {
            // 删除
            PatientInfo info = (PatientInfo) data;
            PopupTipsDialog dialog = new PopupTipsDialog(this, "是否删除【" + info.getName() + "】患者信息？", click -> {
                if (click) {
                    if (mPresenter != null) {
                        mPresenter.removePatient(info.getId());
                    }
                }
            });
            dialog.showAtLocation(view, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        hideInput();
        return super.onTouchEvent(event);
    }

    /**
     * 隐藏软键盘
     */
    private void hideInput() {
        KeyboardUtils.hideSoftInput(this);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void showLoading() {
        notData.setVisibility(View.GONE);
        loading.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        loading.setVisibility(View.GONE);
    }

    @Override
    public void isNotInfo(boolean isValue) {
        notData.setVisibility(isValue ? View.VISIBLE : View.GONE);
    }

    @Override
    public void showInitData(String deptSec, String state) {
        // 设置标题
        if (state.equals("0")) {
            setTitle("现运行信息记录");
        } else if (state.equals("1")) {
            setTitle("关注信息记录");
        } else {
            setTitle("待归档信息记录");
        }

        // 设置院区
        if (deptSec.equals("2")) {
            // 2代表朝阳；
            radioCY.setChecked(true);
            radioCY.setTextColor(getResources().getColor(R.color.common_edit_color));
            radioCY.setBackgroundResource(R.drawable.financial_bg_white_shape);

            radioTZ.setTextColor(getResources().getColor(R.color.common_text_hint_color));
            radioTZ.setBackground(null);
        } else {
            // 3代表通州；
            radioTZ.setChecked(true);
            radioTZ.setTextColor(getResources().getColor(R.color.common_edit_color));
            radioTZ.setBackgroundResource(R.drawable.financial_bg_white_shape);
            radioCY.setTextColor(getResources().getColor(R.color.common_text_hint_color));
            radioCY.setBackground(null);
        }
    }

    @Override
    public void loadDepartment(List<DeptInfo> mList) {
        if (CommonUtils.isNotEmpty(mList)) {
            List<String> mShow = new ArrayList<>();
            mShow.add("全部");

            for (DeptInfo info : mList) {
                mShow.add(info.getName());
            }

            PopupSelectFinancial.ItemClick itemClick = (position, name) -> {
                this.txviDepartment.setText(CommonUtils.isEmptyReturnStr(name));
                if (position == 0) {
                    if (mPresenter != null) {
                        mPresenter.setDeptId("");
                    }
                } else {
                    DeptInfo info = mList.get(position - 1);
                    if (mPresenter != null) {
                        mPresenter.setDeptId(String.valueOf(info.getId()));
                    }
                }

                loadData();
            };
            mPopupDepartment = new PopupSelectFinancial(this, "科室", mShow, itemClick);
        }
    }

    @Override
    public void showLoadingSubmit() {
        if (mDialog != null)
            mDialog.show();
    }

    @Override
    public void hideLoadingSubmit() {
        if (mDialog != null)
            mDialog.hide();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }
}